package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.Product;
import com.example.demo.service.ProductService;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/product")
public class ProductController {
    
    @Resource
    private ProductService productService;
    
    // 获取所有商品列表（匹配前端API调用）
    @GetMapping
    public ResponseEntity<Map<String, Object>> getProducts() {
        try {
            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            
            // 只显示上架商品
            queryWrapper.eq(Product::getIsActive, true);
            
            // 按排序权重和创建时间排序
            queryWrapper.orderByAsc(Product::getSortOrder)
                       .orderByDesc(Product::getCreatedAt);
            
            List<Product> products = productService.list(queryWrapper);
            
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "message", "获取商品列表成功",
                    "data", products
            ));
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "获取商品列表失败: " + e.getMessage()
            ));
        }
    }
    
    // 获取商品列表（分页）
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getProductList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String type) {
        
        try {
            Page<Product> pageInfo = new Page<>(page, size);
            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            
            // 关键词搜索
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.like(Product::getName, keyword)
                           .or()
                           .like(Product::getDescription, keyword);
            }
            
            // 类型筛选
            if (type != null && !type.trim().isEmpty()) {
                queryWrapper.eq(Product::getType, type);
            }
            
            // 只显示上架商品
            queryWrapper.eq(Product::getIsActive, true);
            
            // 按排序权重和创建时间排序
            queryWrapper.orderByAsc(Product::getSortOrder)
                       .orderByDesc(Product::getCreatedAt);
            
            Page<Product> result = productService.page(pageInfo, queryWrapper);
            
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "message", "获取商品列表成功",
                    "data", result
            ));
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "获取商品列表失败: " + e.getMessage()
            ));
        }
    }
    
    // 获取商品详情
    @GetMapping("/detail/{id}")
    public ResponseEntity<Map<String, Object>> getProductDetail(@PathVariable String id) {
        try {
            Product product = productService.getById(id);
            
            if (product != null && product.getIsActive()) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "获取商品详情成功",
                        "data", product
                ));
            } else {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "商品不存在或已下架"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "获取商品详情失败: " + e.getMessage()
            ));
        }
    }
    
    // 根据ID获取商品详情（RESTful风格）
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getProductById(@PathVariable String id) {
        try {
            Product product = productService.getById(id);
            
            if (product != null) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "获取商品详情成功",
                        "data", product
                ));
            } else {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "商品不存在"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "获取商品详情失败: " + e.getMessage()
            ));
        }
    }
    
    // 添加商品（需要登录）
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addProduct(@RequestBody Product product) {
        try {
            // 设置默认值
            if (product.getIsActive() == null) {
                product.setIsActive(true); // 默认上架
            }
            if (product.getToken() == null) {
                product.setToken(0); // 默认token为0
            }
            if (product.getSortOrder() == null) {
                product.setSortOrder(0); // 默认排序权重为0
            }
            
            // 生成商品ID（如果未提供）
            if (product.getId() == null || product.getId().trim().isEmpty()) {
                product.setId("prod_" + System.currentTimeMillis());
            }
            
            boolean saved = productService.save(product);
            
            if (saved) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "添加商品成功"
                ));
            } else {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "添加商品失败"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "添加商品失败: " + e.getMessage()
            ));
        }
    }
    
    // 创建商品（RESTful风格，管理员）
    @PostMapping
    public ResponseEntity<Map<String, Object>> createProduct(@RequestBody Product product) {
        try {
            // 设置默认值
            if (product.getIsActive() == null) {
                product.setIsActive(true);
            }
            if (product.getToken() == null) {
                product.setToken(0);
            }
            if (product.getSortOrder() == null) {
                product.setSortOrder(0);
            }
            
            // 生成商品ID（如果未提供）
            if (product.getId() == null || product.getId().trim().isEmpty()) {
                product.setId("prod_" + System.currentTimeMillis());
            }
            
            boolean saved = productService.save(product);
            
            if (saved) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "创建商品成功",
                        "data", product
                ));
            } else {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "创建商品失败"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "创建商品失败: " + e.getMessage()
            ));
        }
    }
    
    // 更新商品（需要登录）
    @PostMapping("/update")
    public ResponseEntity<Map<String, Object>> updateProduct(@RequestBody Product product) {
        try {
            boolean updated = productService.updateById(product);
            
            if (updated) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "更新商品成功"
                ));
            } else {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "更新商品失败"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "更新商品失败: " + e.getMessage()
            ));
        }
    }
    
    // 更新商品（RESTful风格，管理员）
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateProductById(@PathVariable String id, @RequestBody Product product) {
        try {
            // 设置ID
            product.setId(id);
            
            boolean updated = productService.updateById(product);
            
            if (updated) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "更新商品成功",
                        "data", product
                ));
            } else {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "更新商品失败"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "更新商品失败: " + e.getMessage()
            ));
        }
    }
    
    // 删除商品（需要登录）
    @PostMapping("/delete/{id}")
    public ResponseEntity<Map<String, Object>> deleteProduct(@PathVariable String id) {
        try {
            boolean deleted = productService.removeById(id);
            
            if (deleted) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "删除商品成功"
                ));
            } else {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "删除商品失败"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "删除商品失败: " + e.getMessage()
            ));
        }
    }
    
    // 删除商品（RESTful风格，管理员）
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteProductById(@PathVariable String id) {
        try {
            boolean deleted = productService.removeById(id);
            
            if (deleted) {
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "删除商品成功"
                ));
            } else {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "删除商品失败"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "删除商品失败: " + e.getMessage()
            ));
        }
    }
    
    // 上架/下架商品（需要登录）
    @PostMapping("/toggle-status/{id}")
    public ResponseEntity<Map<String, Object>> toggleProductStatus(@PathVariable String id) {
        try {
            Product product = productService.getById(id);
            
            if (product != null) {
                // 切换状态
                product.setIsActive(!product.getIsActive());
                boolean updated = productService.updateById(product);
                
                if (updated) {
                    String statusText = product.getIsActive() ? "上架" : "下架";
                    return ResponseEntity.ok(Map.of(
                            "success", true,
                            "message", "商品" + statusText + "成功"
                    ));
                } else {
                    return ResponseEntity.ok(Map.of(
                            "success", false,
                            "message", "操作失败"
                    ));
                }
            } else {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "商品不存在"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "操作失败: " + e.getMessage()
            ));
        }
    }
}
